<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
  import fs from 'fs'
  import http from 'http'
  import url from 'url'
  import Login from './api/login'
  import {checkFolder} from './config/utils'

  export default {
    name: 'am',
    data() {
      return {
        localMaterialFolder: this.$KalixGlobalConfig.LocalMaterialFolder,
        examMaterialFolder: this.$KalixGlobalConfig.ExamMaterialFolder,
        fileName: null
      }
    },
    mounted() {
      // 自动登录和下载素材
      // console.log('APP window.KalixConfig', window.KalixConfig.server)
      // this.$nextTick(() => {
      //   this.autoLogin().then(() => {
      //     this.autoDownload()
      //       this.$http.get('/logout')
      //   }).catch(() => {
      //   })
      // })
    },
    methods: {
      autoLogin() {
        return new Promise((resolve, reject) => {
          let username = 'admin'
          let password = '123'
          Login.remoteLogin({
            'username': username,
            'password': password
          }).then(data => {
            if (data.success) {
              this.$KalixCatch.save('access_token', data.access_token)
              this.$KalixCatch.save('user_token', data.user.token)
              resolve()
            } else {
              this.$KalixMessage.error(data.message)
              reject(new Error(data.message))
            }
          })
        })
      },
      /**
       * 下载素材文件
       * @returns {Promise<void>}
       */
      async autoDownload() {
        let url = '/camel/rest/examcreates/exam/quesids'
        this.$http.get(url).then(res => {
          console.log('1下载素材文件', res)
          // /enrolment/DigitalModeling
          // jsonStr: {mainId:1003740}
          // page: 1
          // limit: 10
          // start: 0
        })
        // let checkFolderFlag = await checkFolder(this.localMaterialFolder)
        // if (!checkFolderFlag) {
        //   let createFolderFlag = await checkFolder(this.localMaterialFolder)
        //   if (createFolderFlag) {
        //     this._getMaterial()
        //   }
        // } else {
        //   this._getMaterial()
        // }
      },
      _getMaterial() {
        let urls = [
          'http://localhost:7780/material/1.zip',
          'http://localhost:7780/material/2.zip',
          'http://localhost:7780/material/3.zip',
          'http://localhost:7780/material/4.zip',
          'http://localhost:7780/material/5.zip',
          'http://localhost:7780/material/6.zip',
          'http://localhost:7780/material/7.zip'
        ]
        this.items = []
        urls.forEach(e => {
          let item = url.parse(e)
          let keyIndex = item.path.lastIndexOf('/')
          this.items.push({
            host: item.hostname,
            port: item.port,
            path: item.path,
            fileName: keyIndex > -1 ? item.path.slice(keyIndex + 1) : null
          })
        })
        this._de(0)
      },
      _end() {
        console.log('_end:')
      },
      _de(idx) {
        if (this.items.length && this.items[idx]) {
          this._downloadFile(this.items[idx], idx)
        } else {
          this._end()
        }
      },
      async _downloadFile({host, port, path, fileName}, idx) {
        let options = {host, port, path}
        let _flag = await checkFolder(this.localMaterialFolder + fileName)
        console.log(`_downloadFile:${this.localMaterialFolder + fileName}`, _flag)
        if (!_flag) {
          http.get(options, res => {
            console.log(`_downloadFile:res.statusCode 112`, res.statusCode)
            if (res.statusCode === 200) {
              let file = fs.createWriteStream(this.localMaterialFolder + fileName)
              res
                .on('data', data => {
                  file.write(data)
                })
                .on('end', () => {
                  file.end()
                  console.log(fileName + ' downloaded to ' + this.localMaterialFolder)
                  this._de(idx += 1)
                })
            }
          })
        } else {
          this._de(idx += 1)
        }
      }
    }
  }
</script>

<style lang="stylus" type="text/stylus">
  @import './assets/stylus/common.styl'
  #app
    height 100%
</style>
